package com.micro.ai.template.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.micro.ai.commons.exception.BusinessException;
import com.micro.ai.template.entity.TemplateShare;
import com.micro.ai.template.mapper.TemplateShareMapper;
import com.micro.ai.template.service.TemplateShareService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.UUID;

/**
 * 模板分享Service实现
 *
 * @author micro-ai
 * @since 0.0.1
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class TemplateShareServiceImpl extends ServiceImpl<TemplateShareMapper, TemplateShare>
        implements TemplateShareService {

    @Override
    @Transactional(rollbackFor = Exception.class)
    public TemplateShare createShare(TemplateShare templateShare) {
        log.info("创建分享链接, templateId: {}, userId: {}", 
                templateShare.getTemplateId(), templateShare.getUserId());

        // 生成分享码
        String shareCode = UUID.randomUUID().toString().replace("-", "").substring(0, 16);
        templateShare.setShareCode(shareCode);
        templateShare.setViewCount(0);
        templateShare.setCreatedAt(LocalDateTime.now());
        
        this.save(templateShare);
        log.info("分享链接创建成功, shareId: {}, shareCode: {}", templateShare.getId(), shareCode);
        
        return templateShare;
    }

    @Override
    public TemplateShare getShareByCode(String shareCode) {
        LambdaQueryWrapper<TemplateShare> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(TemplateShare::getShareCode, shareCode);
        
        TemplateShare share = this.getOne(wrapper);
        if (share == null) {
            throw new BusinessException("分享不存在");
        }
        
        // 检查是否过期
        if (share.getExpireAt() != null && share.getExpireAt().isBefore(LocalDateTime.now())) {
            throw new BusinessException("分享已过期");
        }
        
        // 检查访问次数限制
        if (share.getMaxViews() != null && share.getMaxViews() > 0 && share.getViewCount() >= share.getMaxViews()) {
            throw new BusinessException("分享已达到最大访问次数");
        }
        
        return share;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void revokeShare(String shareId, String userId) {
        log.info("撤销分享, shareId: {}, userId: {}", shareId, userId);

        TemplateShare share = this.getById(shareId);
        if (share == null) {
            throw new BusinessException("分享不存在");
        }

        // 验证权限
        if (!share.getUserId().equals(userId)) {
            throw new BusinessException("无权撤销此分享");
        }

        this.removeById(shareId);
        log.info("分享撤销成功");
    }

    @Override
    public IPage<TemplateShare> getUserShares(String userId, Page<TemplateShare> page) {
        LambdaQueryWrapper<TemplateShare> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(TemplateShare::getUserId, userId)
                .orderByDesc(TemplateShare::getCreatedAt);
        
        return this.page(page, wrapper);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void incrementAccessCount(String shareId) {
        TemplateShare share = this.getById(shareId);
        if (share != null) {
            share.setViewCount(share.getViewCount() + 1);
            this.updateById(share);
        }
    }

    @Override
    public boolean isShareValid(String shareCode) {
        try {
            this.getShareByCode(shareCode);
            return true;
        } catch (BusinessException e) {
            return false;
        }
    }
}

